package com.lich.task;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.lich.dao.AppErrorMapper;
import com.lich.dao.graph.ErrorTimesMapper;
import com.lich.dao.graph.MonthErrorTimesMapper;
import com.lich.dao.graph.WeekErrorTimesMapper;
import com.lich.dao.graph.base.GraphBaseMapper;
import com.lich.entity.graph.ErrorAnalysis;

@Component
@PropertySource("classpath:task.properties")
public class ErrorTimesTask {
	private static Logger logger = LoggerFactory.getLogger(ErrorTimesTask.class);
	@Resource
	AppErrorMapper appErrorMapper;
	@Resource
	ErrorTimesMapper errorTimesMapper;
	@Resource
	WeekErrorTimesMapper weekErrorTimesMapper;
	@Resource
	MonthErrorTimesMapper monthErrorTimesMapper;
	
	//@Scheduled(cron = "0 * * * * ?")
	//@Scheduled(fixedRate = 20000)
	 public void run() {
        System.out.println("测试..........");
    }
	/**
	 * @description:定时任务,转存错误数 到日,周,月表
	 * @author: luosf 
	 * @Time: 2016年9月20日
	 */
	@Scheduled(cron = "${errortimes}")
	public void timedTaskToClientErrorTimes(){
		logger.info("源数据转存日错误数任务开始!");
		int result =-1;
		String strDate=beforNumDay(-1);
		System.out.println(strDate);
		List<ErrorAnalysis> errorAnalysisList = appErrorMapper.selectDayLoginTimesByDate(strDate);
		if(errorAnalysisList!=null && errorAnalysisList.size()>0){
			result = toDayErrorTimes(errorAnalysisList);
			if (result>0){
				logger.info("源数据转存日错误数表成功!");
			}else{
				logger.warn("源数据转存日错误数表失败!");
			}
			
			result = toWeekErrorTimes(errorAnalysisList);
			if (result>0){
				logger.info("源数据转存周错误数表成功!");
			}else{
				logger.warn("源数据转存周错误数表失败!");
			}
			
			result = toMonthErrorTimes(errorAnalysisList);
			if (result>0){
				logger.info("源数据转存月错误数表成功!");
			}else{
				logger.warn("源数据转存月错误数表失败!");
			}
		}
		else{
			logger.warn("当天的源数据表没有数据!");
		}
	}
	/**
	 * @description:转存日错误数
	 * @author: luosf 
	 * @Time: 2016年9月20日  
	 * @param ErrorAnalysisList 源数据集合
	 * @return
	 */
	public int toDayErrorTimes(List<ErrorAnalysis> errorAnalysisList){
			return errorTimesMapper.insertList(errorAnalysisList);
	}
	
	/**
	 * @description:转存周错误数
	 * @author: luosf 
	 * @Time: 2016年9月20日  
	 * @param ErrorAnalysisList 源数据集合
	 * @return
	 */
	public int toWeekErrorTimes(List<ErrorAnalysis> errorAnalysisList){
		int result = -1;
		String strDate = getSunday();
		System.out.println("这周日期:"+strDate);
		List<ErrorAnalysis> weekErrorTimesList = weekErrorTimesMapper.selectByDate(strDate);
		for(ErrorAnalysis ca:weekErrorTimesList){
			ca.setStatisticsDate(getSundayDate());
		}
		if(weekErrorTimesList.size()>0){
			result = saveLoginTimesData(weekErrorTimesMapper,weekErrorTimesList,errorAnalysisList);
		}else{
			result = weekErrorTimesMapper.insertList(errorAnalysisList);
		}
		return result;
	}
	/**
	 * @description:转存月错误数
	 * @author: luosf 
	 * @Time: 2016年9月20日  
	 * @param errorAnalysisList 源数据集合
	 * @return
	 */
	public int toMonthErrorTimes(List<ErrorAnalysis> errorAnalysisList){
		int result = -1;
		String strDate = getMonthday();
		System.out.println("这个月日期:"+strDate);
		List<ErrorAnalysis> monthLoginTimesList = monthErrorTimesMapper.selectByDate(strDate);
		for(ErrorAnalysis ca:errorAnalysisList){
			ca.setStatisticsDate(getMonthdayDate());
		}
		if(monthLoginTimesList.size()>0){
			result = saveLoginTimesData(monthErrorTimesMapper,monthLoginTimesList,errorAnalysisList);
		}else{
			result = monthErrorTimesMapper.insertList(errorAnalysisList);
		}
		return result;
	}
	/**
	 * @description:转存错误数处理
	 * @author: luosf 
	 * @Time: 2016年9月20日  
	 * @param ErrorAnalysisList 源数据集合
	 * @return
	 */
	public int saveLoginTimesData(GraphBaseMapper<ErrorAnalysis> gbm,List<ErrorAnalysis> targetList,List<ErrorAnalysis> originList){
		int result = -1;
		Boolean isExist = false;
		List<ErrorAnalysis> tempOriginList = new ArrayList<ErrorAnalysis>();
		for(ErrorAnalysis cal : originList){
			for(ErrorAnalysis caw : targetList){
				if(cal.getProductId().equals(caw.getProductId())){
					caw.setErrorTimes(cal.getErrorTimes()+caw.getErrorTimes());
					result = gbm.updateLogintimesById(caw);
					if(result<=0){
						return result;
					}
					isExist = true;
				}
			}
			if(!isExist){
				tempOriginList.add(cal);
				isExist = false;
			}
		}
		if(tempOriginList.size()>0){
			result = gbm.insertList(tempOriginList);
		}
		return result;
	}
	
	/**
	* @description: 查询当前日期前x天的日期
    * @author luosf
    * @param day 天数（如果day数为负数,说明是此日期前的天数）
    * @return Date 日期
    */
    public static String beforNumDay(int day){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DAY_OF_YEAR, day);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String newDate = sdf.format(c.getTime());
        return newDate;
    }
    /**
     * @description:获取字符串周日
     * @author: luosf 
     * @Time: 2016年9月20日  
     * @return
     */
    public static String getSunday(){
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_WEEK);
        c.add(Calendar.DAY_OF_YEAR, -day+1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String newDate = sdf.format(c.getTime());
        return newDate;
    }
    /**
     * @description:获取周日日期
     * @author: luosf 
     * @Time: 2016年9月20日  
     * @return
     */
    public static Date  getSundayDate(){
        Calendar c = Calendar.getInstance();
        int num = c.get(Calendar.DAY_OF_WEEK);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        c.set(year, month, day-num+1, 00, 00, 00);
        return c.getTime();
    }
    /**
     * @description:获取月的第一天日期
     * @author: luosf 
     * @Time: 2016年9月20日  
     * @return
     */
    public static Date  getMonthdayDate(){
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        c.set(year, month, 1, 00, 00, 00);
        return c.getTime();
    }
    /**
     * @description:获取字符串月的第一天日期
     * @author: luosf 
     * @Time: 2016年9月20日  
     * @return
     */
    public static String getMonthday(){
    	String newDate = null;
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        if(month<10){
        	String m = "0"+month;
        	newDate = year+"-"+m+"-01";
        }
        else{
        	newDate = year+"-"+month+"-01";
        }
        return newDate;
    } 
    @Test
    public void text(){
    	//OriginalData2GraphDataTask.getMonthdayDate();
    	//OriginalData2GraphDataTask.beforNumDay(0);
    	Integer a =1;
    	Integer b = 1;
    	Integer c =a;
    	if(a.equals(b))
    		System.out.println("bbbb");
    	else if(a.equals(c))
    		System.out.println("ccc");
    }
}
